package com.jz.dynadatasorces.rocketMQ.producer;


import com.alibaba.fastjson.JSONObject;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.jz.dynadatasorces.po.vo.OrderVo;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;


import java.util.UUID;


@Component
public class Myproducer {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void sendMessage(String topic,String msg) {
        rocketMQTemplate.convertAndSend(topic,msg);
    }
    public void sendMessageInTransaction(String topic, String message, OrderVo orderVo) {
            // 计算过期时间戳
            String uuid = UUID.randomUUID().toString().replace("-", "");

            String code = "BAT10015";

        Message<String> build = MessageBuilder.withPayload(message)
                // 根据需要设置
                .setHeader(RocketMQHeaders.TRANSACTION_ID, uuid)
                // 设置一个业务的key,以便事务回查时使用
                .setHeader(RocketMQHeaders.KEYS, code)
                .build();
        // 发送事务消息
            TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(topic, build, orderVo);

        }

    }


